package com.wang.jmonkey.ca.handler.login.request;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.wang.jmonkey.ca.model.AuthParam;
import com.wang.jmonkey.common.constant.SecurityConstant;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Description
 * @Author HeJiawang
 * @Date 2021/5/11 16:37
 */
@Component
public class AuthenticationPostHandler extends AbstractRequestHandler {

    @Override
    public void handler(HttpServletRequest request, AuthParam authParam, RequestHandler chain) {

        if (checkRequestMethod(request, RequestMethod.POST)) {

            try (InputStream input = request.getInputStream(); InputStreamReader isr = new InputStreamReader(input); BufferedReader reader = new BufferedReader(isr); ) {

                StringBuilder sb = new StringBuilder();
                String str;
                while (StrUtil.isNotEmpty((str = reader.readLine()))) {
                    sb.append(str);
                }

                JSONObject json = JSONObject.parseObject(sb.toString());
                if (!ObjectUtils.isEmpty(authParam)) {
                    authParam.setUsername(getValue(json, SecurityConstant.LoginParameter.username.getKey(), StrUtil.EMPTY));
                    authParam.setPassword(getValue(json, SecurityConstant.LoginParameter.password.getKey(), StrUtil.EMPTY));
                    authParam.setCode(getValue(json, SecurityConstant.LoginParameter.code.getKey(), StrUtil.EMPTY));
                    authParam.setDeviceId(getValue(json, SecurityConstant.LoginParameter.deviceId.getKey(), StrUtil.EMPTY));
                    authParam.setOauthType(getValue(json, SecurityConstant.LoginParameter.oauthType.getKey(), SecurityConstant.OAuthType.access_token.getKey()));
                    authParam.setRefreshToken(getValue(json, SecurityConstant.LoginParameter.refreshToken.getKey(), StrUtil.EMPTY));
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        chain.handler(request, authParam, chain);
    }

}
